package com.keson.blueconfig;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;

public class LocationUtil {
	private static GeoCoder mCoder;
	private static String result = "";
	private static int outTime = 3000;//超时时间（毫秒）
	public static String getLocation(double longitude, double latitude) {
		for (int i = 0; i < 10; i++) {
			result = "";
			if(mCoder==null){
				mCoder = GeoCoder.newInstance();
			}
			mCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
				@Override
				public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

				}

				@Override
				public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
					if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
						//没有找到检索结果
						return;
					} else {
						//地址
						ReverseGeoCodeResult.AddressComponent address = reverseGeoCodeResult.getAddressDetail();
						result = address.province+address.city+address.district;
						//详细地址
//					System.out.println(reverseGeoCodeResult.getAddressDetail());
					}
				}
			});
			if(i==0||i==3||i==6||i==9){
				mCoder.reverseGeoCode(new ReverseGeoCodeOption().location(new LatLng(latitude, longitude)));
			}
			int start = 0;
			while (result.equals("")){
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				start+=100;
				if(start>=outTime){
					System.out.println("位置获取3秒超时");
					break;
				}
			}
			if(!result.equals("")){
				break;
			}
			System.out.println("位置获取尝试第"+(i+2)+"次");

		}
		if(result.equals("")){
			new Thread(new Runnable() {
				@Override
				public void run() {
					result = HttpUtil.get("http://47.94.80.3:8080/quake/location","lon="+longitude+"&lat="+latitude);
					if(result.indexOf("(")>-1){
						result = "";
					}
				}
			}).start();
			while (result.equals("")){
				int start = 0;
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				start+=100;
				if(start>=outTime){
					System.out.println("位置获取3秒超时");
					break;
				}
			}
		}
		return result;

//		URL url;
//		try {
//			url = new URL("http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location="+latitude+","+longitude+"&output=json&pois=1&ak=Vaz2b04EoRifFPki9yCA3P0L1hDHWLl6");
//			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//			InputStream is = connection.getInputStream();
//			InputStreamReader inputStreamReader = new InputStreamReader(is,"UTF-8");
//            BufferedReader reader = new BufferedReader(inputStreamReader);
//
//            String tempLine;
//            StringBuffer resultBuffer = new StringBuffer();
//			while ((tempLine = reader.readLine()) != null) {
//
//				resultBuffer.append(tempLine);
//            }
//			String location = resultBuffer.toString();
//			JSONObject obj = JSONObject.parseObject(location.substring(location.indexOf("&&renderReverse")+16, location.length()-1));
//			JSONObject address = obj.getJSONObject("result").getJSONObject("addressComponent");
//			return address.getString("province")+address.getString("city")+address.getString("district");
//		} catch (MalformedURLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		return "";
	}

	public static double algorithm(double longitude1, double latitude1, double longitude2, double latitude2) {
		double Lat1 = rad(latitude1); // 纬度
		double Lat2 = rad(latitude2);
		double a = Lat1 - Lat2;//两点纬度之差
		double b = rad(longitude1) - rad(longitude2); //经度之差
		double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(Lat1) * Math.cos(Lat2) * Math.pow(Math.sin(b / 2), 2)));//计算两点距离的公式
		s = s * 6378137.0;//弧长乘地球半径（半径为米）
		s = Math.round(s * 10000d) / 10000d;//精确距离的数值
		return s;
	}

	private static double rad(double d) {
		return d * Math.PI / 180.00; //角度转换成弧度
	}

	/**
	 * 根据一个经纬度及距离角度，算出另外一个经纬度
	 * @param {*} lng 经度 113.3960698
	 * @param {*} lat 纬度 22.941386
	 * @param {*} brng 方位角 45 ---- 正北方：000°或360° 正东方：090° 正南方：180° 正西方：270°
	 * @param {*} dist 90000距离(米)
	 *
	 * 1、角度转换为弧度公式：弧度=角度×(π ÷度180 )
	 * 2、弧度转换为角度公式： 角度=弧度×（180÷π）
	 */
	public static double[] getAnotherLngLat (double lng, double lat, double brng, double dist) {
		//大地坐标系资料WGS-84 长半径a=6378137 短半径b=6356752.3142 扁率f=1/298.2572236
		double a = 6378137;
		double b = 6356752.3142;
		double f = 1 / 298.257223563;

		double lon1 = lng * 1;
		double lat1 = lat * 1;
		double s = dist;
		double alpha1 = brng * (Math.PI / 180);//mapNumberUtil.rad(brng);
		double sinAlpha1 = Math.sin(alpha1);
		double cosAlpha1 = Math.cos(alpha1);

		//var tanU1 = (1 - f) * Math.tan(mapNumberUtil.rad(lat1));
		double tanU1 = (1 - f) * Math.tan(lat1 * (Math.PI / 180));
		double cosU1 = 1 / Math.sqrt((1 + tanU1 * tanU1)), sinU1 = tanU1 * cosU1;
		double sigma1 = Math.atan2(tanU1, cosAlpha1);
		double sinAlpha = cosU1 * sinAlpha1;
		double cosSqAlpha = 1 - sinAlpha * sinAlpha;
		double uSq = cosSqAlpha * (a * a - b * b) / (b * b);
		double A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
		double B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));

		double sigma = s / (b * A), sigmaP = 2 * Math.PI;
		double sinSigma = 0;
		double cosSigma = 0;
		double cos2SigmaM = 0;
		while (Math.abs(sigma - sigmaP) > 1e-12) {
			cos2SigmaM = Math.cos(2 * sigma1 + sigma);
			sinSigma = Math.sin(sigma);
			cosSigma = Math.cos(sigma);
			double deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) -
					B / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM)));
			sigmaP = sigma;
			sigma = s / (b * A) + deltaSigma;
		}

		double tmp = sinU1 * sinSigma - cosU1 * cosSigma * cosAlpha1;
		double lat2 = Math.atan2(sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1,
				(1 - f) * Math.sqrt(sinAlpha * sinAlpha + tmp * tmp));
		double lambda = Math.atan2(sinSigma * sinAlpha1, cosU1 * cosSigma - sinU1 * sinSigma * cosAlpha1);
		double C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha));
		double L = lambda - (1 - C) * f * sinAlpha *
				(sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));

		double revAz = Math.atan2(sinAlpha, -tmp); // final bearing

		double[] lngLatObj = { lon1 + L * (180 / Math.PI), lat2 * (180 / Math.PI) };
		return lngLatObj;
	}



	public static void main(String[] args) {
		getLocation(117.1,25.1);
	}
}
